package cn.wolfcode.trip.admin.web.filter;


import cn.wolfcode.trip.admin.util.UploadUtil;
import org.apache.commons.io.FileUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

//图片过滤器
public class ImageFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        //1:获取图片名称: /upload/xxx.jpg
        //先强转为http
        HttpServletRequest req = (HttpServletRequest) request;
        //获得URI,利用HttpServletRequest的方法,获得URI
        String image = req.getRequestURI();
        //2:判断获取图片名称是否存在共享服务器中:
        //new了一个,可是没写流进去
        File file = new File(UploadUtil.IMG_BASE_PATH, image);

        //判断文件是否存在
        if (file.exists()) {
            //3.如果存在,将图片返回给浏览器
            //3.1从图片共享服务器中读取图片获得2进制字节流
            byte[] bytes = FileUtils.readFileToByteArray(file);
            //3.2将图片写出浏览器
            response.getOutputStream().write(bytes);

        }else {
            //4.就是这里不存在的时候,执行放行,让他去搜索项目下的相对路径
            chain.doFilter(request,response);
        }


    }

    @Override
    public void destroy() {

    }
}
